package com.zhangdi.demo.itextpdf;

import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.extgstate.PdfExtGState;
import com.itextpdf.layout.Document;

public class App {
    public static final String DEST = "C:\\Users\\Administrator\\Desktop\\pdftest\\歹毒的金刀计1.pdf";
    public static final String IMG = "C:\\Users\\Administrator\\Desktop\\pdftest\\watermark.png";
    public static final String SRC = "C:\\Users\\Administrator\\Desktop\\pdftest\\歹毒的金刀计.pdf";

    public static void main(String[] args) throws Exception {
        App app = new App();
        app.manipulatePdf(DEST);
    }


    void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
        Document doc = new Document(pdfDoc);
        ImageData img = ImageDataFactory.create(IMG);
        img.setXYRatio(45);
        float w = img.getWidth();
        float h = img.getHeight();

        PdfExtGState gs1 = new PdfExtGState().setFillOpacity(.3f);

        for (int i = 1; i <= pdfDoc.getNumberOfPages(); i++) {

            PdfPage pdfPage = pdfDoc.getPage(i);
            Rectangle pageSize = pdfPage.getPageSizeWithRotation();

            // When "true": in case the page has a rotation, then new content will be automatically rotated in the
            // opposite direction. On the rotated page this would look as if new content ignores page rotation.
            pdfPage.setIgnorePageRotationForContent(true);

            PdfCanvas over = new PdfCanvas(pdfDoc.getPage(i));
            over.saveState();
            over.setExtGState(gs1);

            over.addImageWithTransformationMatrix(img, w, 0, 0, h, pageSize.getWidth() - w, 0, false);
            over.restoreState();
        }

        doc.close();
    }
}